package com.tan.websocket.handler;

import cn.hutool.extra.spring.SpringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Tan
 * @description
 * @date 2025/1/26
 */
@Slf4j
@Component
public class MainWebsocketFrame {

    public static Map<String, MainFrameService> serviceMap = new HashMap<>();

    public void handle(ChannelHandlerContext ctx, WebSocketFrame frame) {
        if (serviceMap.isEmpty()) {
            this.initService();
        }
        MainFrameService service = serviceMap.get(frame.getClass().getSimpleName());
        if (service != null) {
            service.handleMessage(ctx, frame);
        }
    }

    public void initService() {
        Map<String, MainFrameService> service = SpringUtil.getBeansOfType(MainFrameService.class);
        service.forEach((k, v) -> {
            serviceMap.put(v.serviceName(), v);
        });
    }

}
